package me.henhaoji.tokenmgr.web;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.henhaoji.wxtoken.AccessToken;
import me.henhaoji.wxtoken.TokenService;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.SessionAware;








import com.opensymphony.xwork2.ActionSupport;

public class TokenAction extends ActionSupport implements RequestAware,SessionAware, ApplicationAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = -4120091081164857381L;
	public final String LIST = "list";
	public final String ADD = "add";
	public final String INFO = "info";
	protected Map<String, Object> request;
	protected Map<String, Object> session;
	protected Map<String, Object> application;
	TokenService service;
	public String userId;
	public String appId;
	public AccessToken atoken;
	public TokenAction()
	{
		service = TokenService.getInstance();
	}
	public String listAll()
	{
		List<AccessToken> tokenList = service.getTokenList();
		Map<String,Date> dateMap = new HashMap<String,Date>();
		Map<String,String> tmpMap = new HashMap<String,String>();
		Map<String,String> secMap = new HashMap<String,String>();
		for(AccessToken token:tokenList)
		{
			long ein = 0;
			long nows = System.currentTimeMillis()/1000;
			ein = token.getExpires_in()-(nows-token.getUpdateTime());
			token.setExpires(ein);
			Date d = new Date(token.getUpdateTime()*1000);
			dateMap.put(token.getId(), d);
			if(token.getAccess_token()!=null)
			{
				String str_token = null;
				if(token.getAccess_token()!=null&&token.getAccess_token().length()>6)
				str_token=token.getAccess_token().substring(0,5)+"*****";
				tmpMap.put(token.getId(), str_token);
			}
			if(token.getSecret()!=null)
			{
				String secret = token.getSecret();
				secMap.put(token.getId(), secret.substring(0, 5)+"*****");
			}
		}
		request.put("list", tokenList);
		request.put("dateMap", dateMap);
		request.put("secMap", secMap);
		request.put("tmpMap", tmpMap);
		request.put("timer", service.getTimer());
		return LIST;
	}
	public boolean isEmpty(String a)
	{
		if(a!=null&&!"".equals(a))return true;
		else return false;
	}
	public String add()
	{
		return ADD;
	}
	
	public String stopTimer()
	{
		service.stopTimer();
		return listAll();
	}
	public String startTimer()
	{
		service.runTimer();
		return listAll();
	}
	public String initTimer()
	{
		service.initTimer();
		return listAll();
	}
	public String addToken()
	{
		if(isEmpty(atoken.getSecret())||isEmpty(atoken.getId())||isEmpty(atoken.getUserId()))
		{
			boolean res = service.add(atoken);
			if(res)
			{
				request.put("msg", "添加成功");
				return listAll();
			}
			else
			{
				request.put("ftoken", atoken);
				request.put("msg", "可能是secret不正确或其他问题，添加失败！");
				return ADD;
			}
		}
		else
		{
			request.put("msg", "信息不完整，添加失败！");
			return ADD;
		}
	}
	public String delToken()
	{
		AccessToken at = new AccessToken();
		at.setId(appId);
		if(service.delete(at))
		{
			request.put("msg", "删除成功！");
			//return listAll();
		}
		else
		{
			request.put("msg", "删除失败");
		}
		return listAll();
		
	}
	public String refreshAll()
	{
		service.refreshAll();
		request.put("msg", "refreshed All!");
		return listAll();
	}
	public String refreshAllByForce()
	{
		service.refreshAllByForce();
		request.put("msg", "refreshed through weixin All!");
		return listAll();
	}
	public String refreshByUserId()
	{
		service.get(userId);
		request.put("msg", "refreshed one!");
		return listAll();
	}
	public String getToken()
	{
		AccessToken at = service.get(userId);
		if(at!=null)
		{
			JsonConfig config = new JsonConfig();
			long ein = 0;
			long nows = System.currentTimeMillis()/1000;
			ein = at.getExpires_in()-(nows-at.getUpdateTime());
			at.setExpires(ein);
			config.setExcludes(new String[]{"secret","remark","errcode","id","errmsg"});
			request.put("info", JSONObject.fromObject(at,config));
		}
		return SUCCESS;
	}
	public String refreshTokenByForce()
	{
		//service.refreshOneByForce(userId);
		service.getOneByForce(userId);
		AccessToken at = service.get(userId);
		if(at!=null)
		{
			JsonConfig config = new JsonConfig();
			long ein = 0;
			long nows = System.currentTimeMillis()/1000;
			ein = at.getExpires_in()-(nows-at.getUpdateTime());
			at.setExpires(ein);
			config.setExcludes(new String[]{"secret","remark","errcode","id","errmsg"});
			request.put("info", JSONObject.fromObject(at,config));
		}
		return listAll();
	}
	public String getTokenByForce()
	{
		//service.refreshOneByForce(userId);
		service.getOneByForce(userId);
		AccessToken at = service.get(userId);
		if(at!=null)
		{
			JsonConfig config = new JsonConfig();
			long ein = 0;
			long nows = System.currentTimeMillis()/1000;
			ein = at.getExpires_in()-(nows-at.getUpdateTime());
			at.setExpires(ein);
			config.setExcludes(new String[]{"secret","remark","errcode","id","errmsg"});
			request.put("info", JSONObject.fromObject(at,config));
		}
		return SUCCESS;
	}
	public void setRequest(Map<String, Object> request) {
		this.request = request;
	}

	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	public void setApplication(Map<String, Object> application) {
		this.application = application;
	}
	public String getUserId() {
		return userId;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}
	public AccessToken getAtoken() {
		return atoken;
	}
	public void setAtoken(AccessToken atoken) {
		this.atoken = atoken;
	}
	public String getAppId() {
		return appId;
	}
	public void setAppId(String appId) {
		this.appId = appId;
	}
	
}
